package com.example.myproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.myproject.dto.SignInResponse;
import com.example.myproject.mapper.SignLogMapper;
import com.example.myproject.mapper.UserMoneyMapper;
import com.example.myproject.model.SignLog;
import com.example.myproject.model.UserMoney;
import com.example.myproject.service.SignInService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Random;

@Service
public class SignInServiceImpl implements SignInService {

    @Autowired
    private SignLogMapper signLogMapper;

    @Autowired
    private UserMoneyMapper userMoneyMapper;

    private final Random random = new Random();

    @Override
    @Transactional
    public SignInResponse signIn(Long userId) {
        // 检查今日是否已签到
        LocalDate today = LocalDate.now();
        if (signLogMapper.countSignInToday(userId, today) > 0) {
            throw new RuntimeException("今日已签到");
        }

        // 生成随机奖励
        int magicValue = random.nextInt(50) + 1; // 1-50魔力值
        int points = random.nextInt(20) + 1; // 1-20积分

        // 保存签到记录
        SignLog signLog = new SignLog();
        signLog.setUserId(userId);
        signLog.setSignDate(today);
        signLog.setRewardPoint(points);
        signLog.setRewardMagicvalue(magicValue);
        signLogMapper.insert(signLog);

        // 更新用户资金
        UserMoney userMoney = userMoneyMapper.selectById(userId);
        if (userMoney == null) {
            userMoney = new UserMoney();
            userMoney.setUserId(userId);
            userMoney.setPoint(0.0);
            userMoney.setTicket(0.0);
            userMoney.setMagicvalue(0.0);
        }
        userMoney.setPoint(userMoney.getPoint() + points);
        userMoney.setMagicvalue(userMoney.getMagicvalue() + magicValue);
        userMoneyMapper.updateById(userMoney);

        // 构建响应
        SignInResponse response = new SignInResponse();
        response.setMessage("签到成功");

        SignInResponse.Reward reward = new SignInResponse.Reward();
        reward.setPoints(points);
        reward.setMagicValue(magicValue);
        response.setReward(reward);

        return response;
    }
}